package com.zycfc.zsf.boot.util.net;

import java.io.*;
import java.net.*;
import java.util.*;
import org.slf4j.*;

public class InetUtil
{
    private static final Logger log;
    
    public static InetAddress findFirstNonLoopbackAddress() {
        InetAddress result = null;
        try {
            int lowest = Integer.MAX_VALUE;
            final Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
            while (nics.hasMoreElements()) {
                final NetworkInterface ifc = nics.nextElement();
                if (ifc.isUp()) {
                    InetUtil.log.trace("Testing interface: " + ifc.getDisplayName());
                    if (ifc.getIndex() < lowest || result == null) {
                        lowest = ifc.getIndex();
                    }
                    else if (result != null) {
                        continue;
                    }
                    final Enumeration<InetAddress> addrs = ifc.getInetAddresses();
                    while (addrs.hasMoreElements()) {
                        final InetAddress address = addrs.nextElement();
                        if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
                            InetUtil.log.trace("Found non-loopback interface: " + ifc.getDisplayName());
                            result = address;
                        }
                    }
                }
            }
        }
        catch (IOException ex) {
            InetUtil.log.error("Cannot get first non-loopback address", (Throwable)ex);
        }
        if (result != null) {
            return result;
        }
        try {
            return InetAddress.getLocalHost();
        }
        catch (UnknownHostException e) {
            InetUtil.log.warn("Unable to retrieve localhost");
            return null;
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)InetUtil.class);
    }
}
